from sqlalchemy import String
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import Session
from sqlalchemy.orm import DeclarativeBase
from ..db import get_db

class Base(DeclarativeBase):
  pass
  
class User(Base):
  __tablename__ = "user"

  uid: Mapped[int] = mapped_column(primary_key=True)
  name: Mapped[str] = mapped_column(String(255))
  gender: Mapped[str]= mapped_column(String(255))

  def to_json(self):
    return {
      'uid':self.uid,
      'name':self.name,
      'gender':self.gender,
    }

def get_user_list(kw=None,page:int=1,size:int=10):
  if page<1:
    page=1
  engine = get_db()
  if engine is None:
    return None
  session = Session(engine)
  query = session.query(User)
  query = query.order_by(User.uid.asc())
  if kw is not None and kw!='':
    query = query.where(User.name.like(kw))
  total=query.count()
  items = query.offset((page-1)*size).limit(size).all()
  return items,total

def add_user(user:User):
  engine = get_db()
  if engine is None:
    return None
  session = Session(engine)
  session.add(user)
  session.commit()

def update_user(user:User):
  engine = get_db()
  if engine is None:
    return None
  session = Session(engine)
  session.query(User).where(User.uid==user.uid).update({User.name:user.name,User.gender:user.gender})
  session.commit()